package CeShi;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
 * 将指定目录下的所有文件中的单词统计出来，并存放到另一个文件中
 */
public class Test02 {
    static HashMap<String,Integer> map;
    public static void main(String[] args) {
        File file=new File("E:\\测试2");
        StringBuffer str=new StringBuffer();
        File file1=new File("E:\\测试2\\Test.txt");
        if(!file.isDirectory()){
            System.out.println("文件传入有误！");
            return;
        }
        //读取文件内容
        str=duQu(file);
        //拆分统计每个单词出现的次数
        tongJi(str);
        //在文件中存放每个单词出现的次数
        cunFang(file1);

    }

    private static void cunFang(File file) {
        Set<String> keySet=map.keySet();
        BufferedWriter bw=null;
        try {
            bw= new BufferedWriter(new FileWriter(file));
            Iterator<String> it=keySet.iterator();
            while(it.hasNext()){
                String key=it.next();
                Integer value=map.get(key);
                bw.write( key+"-->"+value+"次");
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (null!=bw){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    private static void tongJi(StringBuffer str) {
        String[] strs=str.toString().split(" ");
        map=new HashMap<String,Integer>();
        for(String key:strs){
            if(!map.containsKey(key)){
                map.put(key, 1);
            }else{
                map.put(key,map.get(key)+1);
            }
        }
    }


    private static StringBuffer duQu(File file) {
        StringBuffer str=new StringBuffer();
        File[] files=file.listFiles();
        BufferedReader br=null;
        for (File fi:files) {
            try {
                br=new BufferedReader(new FileReader(fi));
                while(true){
                    String line= br.readLine();
                    if (line==null){
                        break;
                    }
                    str.append(line);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (null!=br){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return str;
    }
}
